<?php

namespace Modules\Car\Http\Controllers\Api;

use App\Events\NotifyEvent;
use App\Helpers\Constant;
use App\Helpers\NewBaseData;
use App\Helpers\ResponseData;
use Carbon\Carbon;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\Car\Entities\CarOrder;
use Modules\Car\Entities\RecognizeDrivingLicense;
use Modules\Car\Entities\Reminder;
use Modules\Car\Http\Requests\Order\OrderRequest;

//店长
class ShopManagerController extends Controller
{
    use ResponseData,NewBaseData;
    /**
     * 店长 订单列表
     */
    public $days = 0;
    public  $hours = 0;
    //获取租期
    public function leaseDay(Request $request){
        $lease = $request->input('lease',0);
        $size = $request->input('size',10);
        $user = $request->user();
        if($user->post_id==1){
            switch ($lease){
                case 1://逾期
                    $model = $this->searchOrderModel($request);
                    $model = $model
                        ->where('pre_return_time','<',now())
                        ->where('status',5)
                        ->orderByDesc('id')
                        ->paginate($size);
                    break;
                case 2: //今日收车
                    $model = $this->searchOrderModel($request);
                    $model = $model
                        ->whereBetween('pre_return_time',[\Illuminate\Support\Carbon::today(),Carbon::tomorrow()])
                        ->where('status',5)
                        ->orderByDesc('id')
                        ->paginate($size);
                    break;
                case 3://明日收车
                    $model = $this->searchOrderModel($request);
                    $model = $model
                        ->where('pre_return_time','>',Carbon::tomorrow())
                        ->where('pre_return_time','<',date('Y-m-d',strtotime(now()->addDays(2))))
                        ->where('status',5)
                        ->orderByDesc('id')
                        ->paginate($size);
                    break;
                default:
                    $model = $this->searchOrderModel($request);
                    if($user->department_id==1){
                        $model = $model
                            ->where('status',5)
                            ->orderByDesc('id')
                            ->paginate($size);
                    }else{
                        $model = $model
                            ->where('status',5)
                            ->orderByDesc('id')
                            ->where('department',$user->department_id)
                            ->paginate($size);
                    }
            }
        }else{
            switch ($lease){
                case 1://逾期
                    $model = $this->searchOrderModel($request);
                    $model = $model
                        ->where('pre_return_time','<',now())
                        ->where('status',5)
                        ->where('department',$user->department_id)
                        ->orderByDesc('id')
                        ->paginate($size);
                    break;
                case 2: //今日收车
                    $model = $this->searchOrderModel($request);
                    $model = $model
                        ->whereBetween('pre_return_time',[\Illuminate\Support\Carbon::today(),Carbon::tomorrow()])
                        ->where('status',5)
                        ->where('department',$user->department_id)
                        ->orderByDesc('id')
                        ->paginate($size);
                    break;
                case 3://明日收车
                    $model = $this->searchOrderModel($request);
                    $model = $model
                        ->where('pre_return_time','>',Carbon::tomorrow())
                        ->where('pre_return_time','<',date('Y-m-d',strtotime(now()->addDays(2))))
                        ->where('status',5)
                        ->where('department',$user->department_id)
                        ->orderByDesc('id')
                        ->paginate($size);
                    break;
                default:
                    $model = $this->searchOrderModel($request);
                    if($user->department_id==1){
                        $model = $model
                            ->where('status',5)
                            ->where('department',$user->department_id)
                            ->orderByDesc('id')
                            ->paginate($size);
                    }else{
                        $model = $model
                            ->where('status',5)
                            ->where('department',$user->department_id)
                            ->orderByDesc('id')
                            ->where('department',$user->department_id)
                            ->paginate($size);
                    }
            }
        }

        return $this->success($model);
    }

    public function list(Request $request){
        $user = $request->user();
        if(!$user->department_id){
            return $this->failed('请使用店长登录1',201);
        }
        $process_status = $request->input('process_status','');
        $source = $request->input('source','');
        $size = $request->input('size',10);
        $status = $request->input('status',0);
        $is_online = $request->input('is_online',0);
        $model = $this->getNewOrderModel();
        $model = $model
            ->when($process_status,function($query)use($process_status){
                $arr =  explode(',',$process_status);
                $query->whereIn('process_status',$arr);
            })
            ->when($source,function($query)use($source){
                $query->where('source',$source);
            });
        if($is_online&&$is_online==1){//线上
            $model->whereNotNull('openid');
        }else{
            $model->whereNull('openid');
        }
            if($request->filled('search')){
                $model->where('phone',$request->search)
                    ->orWhere('wx_name',$request->search)
                    ->orWhere('nickname',$request->search)
                    ->orWhere('nickname',$request->search)
                    ->orWhere('customer_name',$request->search)
                    ->orWhere('gear_car_name',$request->search)
                    ->orWhere('gear_car_name',$request->search)
                    ->orWhere('plate_number',$request->search);
            }
            if($status==Constant::ORDER_CREATE){
                $model
                    ->where('status',Constant::ORDER_CREATE);
                if($user->post_id!=3){
                    $model->where('department',$user->department_id);
                }
                $order =  $model->when($process_status,function($query)use($process_status){
                        $arr =  explode(',',$process_status);
                        $query->whereIn('process_status',$arr);
                    })
                    ->paginate($size);
            }else{
                $model
                    ->when($status,function($query)use($status){
                        $arr =  explode(',',$status);
                        $query->whereIn('status',$arr);
                    })
                    ->when($process_status,function($query)use($process_status){
                        $arr =  explode(',',$process_status);
                        $query->whereIn('process_status',$arr);
                    });
                if($user->post_id!=3){
                    $model->where('department',$user->department_id);
                }
                $order = $model->paginate($size);
            }

        return $this->success($order);
    }
    //获取所有小程序预订单
    public function OrderForm(CarOrder $model,Request $request){
        $user = $request->user();
        // if($user->role&&$user->role==1){
        // }else{
        //     if(!$user->department_id){
        //         return $this->failed('请使用店长登录2',201);
        //     }
        // }
        $size = $request->input('size',10);
        $status = $request->input('status','');
        $is_online = $request->input('is_online','');
        $model = $this->searchOrderModel($request);
        if($user->post_id==2){
           $model = $model->where('department',$user->department_id);
        }
        $model = $model
            ->with(['changeCar'])
            ->when($status,function($query)use($status){
                $status = explode(",",$status);
                $query->whereIn('status',$status);
            })
            ->when($is_online,function($query)use($is_online){
                if($is_online==1){
                    $query->where('openid','<>','');
                }elseif($is_online==2){
                    $query->where('openid','');
                }
            });

        $order = $model->orderBy('status', 'desc')->orderBy('created_at', 'desc')->paginate($size);
        return $this->success($order);
    }
    /**
     * 待还车订单进行后台还车
     */
    public function return(OrderRequest $request){
        $order = CarOrder::query()
            ->where('order_sn',$request->order_sn)
            ->where('status',Constant::ORDER_USING)
            ->first();
        if($order){
            // 订单是否已被接单
            // if($order->return_employer_id!=0){
            //     return $this->failed('订单已被接单',201);
            // }else{
                $start = $order->fetch_time;
                $end = $request->return_time??now();
                $order->process_status = Constant::STATISTICS_WAITING;//保存
                $order->status = Constant::ORDER_CLOSED;
                $order->return_time = $end;//实际还车时间
                $days = $this->diffDays($start,$end);
                $hours = $this->lastHours($start,$end);
                if($days>0){
                    $order->lease_days = $days;
                }else{
                    $order->lease_days = 1;
                }
                $order->return_employer_id = $request->return_employer_id;
                $order->return_employer_nickname = $request->return_employer_nickname;
                $order->return_employer_phone = $request->return_employer_phone;
                if($request->return_employer_time){
                    $order->return_employer_time = $request->return_employer_time;
                }
                $order->clieaner_can_time = $request->clieaner_can_time;
                $order->fetch_hours = $hours;
                $order->return_position = $request->return_position;
                $order->send_clear_order_lasttime = $request->return_employer_time;
                $order->is_send_clear_order = 2;
                //释放库存
                $this->confirmCar($order->gear_car_id);
                $order->save();
                event(new NotifyEvent($order,config('wechat.notify.mini.ReturnNotify')));
                return $this->success('更新成功');
            // }
        }else{
            return $this->failed('订单不存在',201);
        }
    }
    //店长释放库存
    public function freed($request){
        RecognizeDrivingLicense::query()
            ->where('id',$request->gear_car_id)
            ->where('use_status',Constant::CAR_USE_STATUS_WAIT_STATISTICS)
            ->update(['use_status'=>Constant::CAR_USE_STATUS_EMPTY,'is_used'=>Constant::CAR_EMPTY]);
        return $this->success('请求成功');
    }
    /**
     * 确认还车
     */
    public function confirmReturn(Request $request){
        $order = CarOrder::query()
            ->where('order_sn',$request->order_sn)
            ->first();
        if($order){
            $order->status = Constant::ORDER_CLOSED;
            $order->process_status = Constant::STATISTICS_WAITING;
            //实际还车时间
            $order->return_time = now();
            //实际天数
            $this->diffDays($order->fetch_time, now());
            $order->lease_days = $this->days;
            //实际小时数
            $order->fetch_hours = $this->hours;
            //释放库存
            $this->confirmCar($order->gear_car_id);
            $order->save();
            return $this->success('确认成功');
        }else{
            return $this->failed('订单不存在',201);
        }
    }
    protected function confirmCar($gear_car_id){
        RecognizeDrivingLicense::query()
            ->where('id',$gear_car_id)
           // ->where('use_status',Constant::CAR_USE_STATUS_EMPTY)
            ->update(['is_used'=>Constant::CAR_EMPTY]);
    }

    /**
     * 设置定时提醒
     */
    public function reminder(Request $request){
        $order = CarOrder::query()
            ->where('order_sn',$request->order_sn)
            ->where('process_status',Constant::STATISTICS_FINISHED)
            ->where('status',Constant::ORDER_CLOSED)
            ->first();
        if($order){
            if(is_array($request->data)){
                $data = $request->data;
            }else{
                $data = json_decode($request->data,true);
            }
            foreach ($data as $item){
                $res = ['order_sn'=>$request->order_sn,'contents'=>$item['contents'],'reminder'=>$item['reminder'],'type'=>$item['type']];
                if(isset($item['id'])){
                    Reminder::query()->where('id',$item['id'])->update($res);
                }else{
                    Reminder::query()->insert($res);
                }
            }
            event(new NotifyEvent($order,config('wechat.notify.mini.Reminder')));
            return $this->success('确认成功');
        }else{
            return $this->failed('订单不存在',201);
        }
    }
    //获取reminder列表
    public function reminderList(Request $request){
        $reminder = Reminder::query()->where('order_sn',$request->order_sn)->get();
        if($reminder){
            return $this->success($reminder);
        }else{
            return [];
        }
    }
    //设置送车人员
    public function setSendCarMember(Request $request){
        $order = CarOrder::query()->where('order_sn',$request->order_sn)->first();
        if(!$order){
            return $this->failed('订单不存在',201);
        }
        $order->send_employer_id = $request->send_employer_id??0;
        $order->send_employer_nickname = $request->send_employer_nickname??'';
        $order->save();
        return $this->success('操作成功');
    }
    //店长确认订单
    public function ConfirmOrder(Request $request){

        $order = CarOrder::query()->where('status',1)->where('order_sn',$request->order_sn)->first();
        if(!$order){
            return $this->failed('订单不存在',201);
        }
        $user = $request->user();
        $order->status = Constant::ORDER_IS_CONFIRM;
        if($request->filled('source')){
            $order->source = $request->source;
        }
        if($request->filled('department_id')){
            $order->department = $user->department_id;
        }
        $order->save();
        event(new NotifyEvent($order,config('wechat.notify.mini.AcceptOrder')));
        return $this->success('确认成功');
    }

    //待出车数据
    public function PerparatoryInfo(Request $request){
        $lease = $request->input('lease',0);
        $size = $request->input('size',10);


        switch ($lease){
            case 1://已取消订单
                $model = $this->searchOrderModel($request);
                $model = $model
                    ->whereIn('status',[-1,-2,-3]);
                    // ->where('pre_fetch_time','<',now());
                break;
            case 2: //今日收车
                $model = $this->searchOrderModel($request);
                $model = $model
                    ->where('status',Constant::ORDER_IS_CONFIRM)
                    ->whereBetween('pre_fetch_time',[\Illuminate\Support\Carbon::today(), \Carbon\Carbon::tomorrow()]);
                break;
            case 3://明日收车
                $model = $this->searchOrderModel($request);
                $model = $model
                    ->where('status',Constant::ORDER_IS_CONFIRM)
                    ->where('pre_fetch_time','>', \Illuminate\Support\Carbon::tomorrow())
                    ->where('pre_fetch_time','<',now()->addDays(2));
                break;
            case 4://三天内收车
                $model = $this->searchOrderModel($request);
                $model = $model
                    ->where('status',Constant::ORDER_IS_CONFIRM)
                    ->where('pre_fetch_time','>',Carbon::tomorrow())
                    ->where('pre_fetch_time','<',now()->addDays(3));
                break;
            default:
                $model = $this->searchOrderModel($request);
                $model = $model
                    ->where('status',Constant::ORDER_IS_CONFIRM);
        }
        //小程序订单
        if($request->filled('isopenid')){
            if($request->isopenid==1){
                $model = $model->where('openid','<>','');
            }else{
                $model = $model->where('openid','');
            }
        }
        if($request->filled('department')){
            $model = $model->where('department',$request->department);
        }
//        else{
//            $user = $request->user();
//            if($user->post_id==2){
//                if($user->department_id){
//                    $model = $model->where('department',$user->department_id);
//                }
//            }
//
//
//        }
        $model = $model

            ->orderBy('pre_fetch_time','asc')
            ->paginate($size);
        return $this->success($model);
    }
    //回车接口
    public function WaitCloseCarInfo(Request $request){
        $lease = $request->input('lease',0);
        $size = $request->input('size',10);
        switch ($lease){
            case 1://逾期
                $model = $this->searchOrderModel($request);
                $model = $model
                    ->where('pre_return_time','<',now());
                break;
            case 2: //今日收车
                $model = $this->searchOrderModel($request);
                $model = $model
                    ->whereBetween('pre_return_time',[\Illuminate\Support\Carbon::today(), \Carbon\Carbon::tomorrow()]);
                break;
            case 3://明日收车
                $model = $this->searchOrderModel($request);
                $model = $model
                    ->where('pre_return_time','>', \Illuminate\Support\Carbon::tomorrow())
                    ->where('pre_return_time','<',date('Y-m-d',strtotime(now()->addDays(2))));
                break;
            case 4://三天内收车
                $model = $this->searchOrderModel($request);
                $model = $model
                    ->where('pre_return_time','>',now())
                    ->where('pre_return_time','<',now()->addDays(3));
                break;
            default:
                $model = $this->searchOrderModel($request);
        }
        $model = $model
            ->where('process_status',2)
            ->where('is_sign_contract',3)
            ->where('return_employer_id',0)
            ->orderBy('pre_return_time','asc')
            ->paginate($size);
        return $this->success($model);
    }
    //回车数量接口
    public function WaitCloseCarInfoTotal(Request $request){
        $model = $this->searchOrderModel($request);
        $model = $model->where('process_status',2)->where('is_sign_contract',3)->where('return_employer_id',0);
        $conttotal = $model->get()->count();
        $model2 = clone $model;
        $model3 = clone $model;
        $model4 = clone $model;
        $contday = $model2->whereBetween('pre_return_time',[\Illuminate\Support\Carbon::today(), \Carbon\Carbon::tomorrow()])->get()->count();
        $conttom = $model3
                    ->where('pre_return_time','>', \Illuminate\Support\Carbon::tomorrow())
                    ->where('pre_return_time','<',date('Y-m-d',strtotime(now()->addDays(2))))->get()->count();
        $contthree = $model4
                    ->where('pre_return_time','>',now())
                    ->where('pre_return_time','<',now()->addDays(3))->get()->count();
        return $this->success(compact('contday','conttom','contthree','conttotal'));
    }
//    确认改价功能
    public function confirmChangePrice(Request $request){
        $order = CarOrder::query()->where('order_sn',$request->order_sn)->first();
        if(!$order){
            return $this->failed('订单不存在',201);
        }
        $order->confirm_change_price = 2;
        $order->save();
        return $this->success('操作成功');
    }
    //选车位置
    public function choosePosition(CarOrder $model,Request $request){
        $order = $model->where('order_sn',$request->order_sn)->first();
        if(!$order){
            return $this->failed('订单不存在',201);
        }
        $order->choose_position=$request->choose_position;
        $order->save();
        return $this->success('更新成功');
    }
}
